package priv.bestbeat.cloud.user.advices;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import priv.bestbeat.cloud.common.enums.LogPrefixEnum;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统全局异常告知
 * <b>该异常处理不会产生连锁，即处理方法中再抛出异常，不会被其他异常处理方法捕获</b>
 * @author 张渠钦
 * @date 2021/12/9 16:33
 */
@RestControllerAdvice
@Slf4j
public class SystemGlobalExceptionAdvice {

    /**
     * web请求参数校验异常
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();

        if (bindingResult.hasGlobalErrors()) {
            log.error("{} {}", LogPrefixEnum.REQUEST_VALIDATION_ERROR,ex.getMessage());
            return ResponseEntity.internalServerError().contentType(MediaType.APPLICATION_JSON).body("system error");
        }
        log.error("{} {}",LogPrefixEnum.REQUEST_VALIDATION,ex.getMessage());
        Map<String,String> errorMap = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
        return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON).body(errorMap);
    }

    /**
     * 未识别异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public ResponseEntity<?> handleThrowable(Throwable ex) {
        log.error("{} {}",LogPrefixEnum.SYSTEM_ERROR,ex.getMessage());
        return ResponseEntity.internalServerError().contentType(MediaType.APPLICATION_JSON).body("system error");
    }
}
